package com.thread.demo11;

import java.util.Date;

public class ThreadInterrupt {
	
	private static void test0() throws InterruptedException{
		Thread aa = new Example3();
		aa.start();
		Thread.sleep(3000);
		aa.interrupt();// 等中断信号量设置后再调用
		Thread.sleep(3000);
		System.out.println("Stopping application...");
	}
	
	private static void test1() throws InterruptedException{
		Runner one = new Runner();
		Thread aa = new Thread(one,"aa");
		aa.start();
		Thread.sleep(3000);
		aa.interrupt();// 等中断信号量设置后再调用
		Thread.sleep(3000);
		System.out.println("Stopping application...");
	}
	
	private static void test2(){
		Thread thread = new Thread(()->{
			for (int i = 0; i < 50000; i++) {
	            System.out.println("i=" + (i + 1));
	        }
		});
		thread.start();
        try {
        	Thread.sleep(1000);
            thread.interrupt();
            //清理中断状态
            System.out.println("是否已经停止 1？="+Thread.interrupted());
            System.out.println("是否已经停止 2？="+Thread.interrupted());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("end!");
	}
	
	private static void test3(){
		Thread thread = new Thread(()->{
			for (int i = 0; i < 50000; i++) {
				System.out.println("i=" + (i + 1));
			}
		});
		thread.start();
        try {
            Thread.sleep(1);
            thread.interrupt();
            //没有清理中断状态值
            System.out.println("是否已经停止 1？=" + thread.isInterrupted());
            System.out.println("是否已经停止 2？=" + thread.isInterrupted());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("end!");
	}
	
	public static void main(String[] args) throws InterruptedException {
		
//		test0();
		test1();
//		test2();
//		test3();
		
	}

	static class Runner implements Runnable{
		@Override
		public void run() {
			while (!Thread.currentThread().isInterrupted()){
//				try {
//					Thread.sleep(1000);
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//					Thread.currentThread().interrupt();
//				}
				System.out.println(Thread.currentThread().isInterrupted()+"========"+new Date()+Thread.currentThread().getName());
			}
			System.out.println(Thread.currentThread().isInterrupted()+"====跳出循环===="+new Date());
		}
	}
}
